package com.travel.api.service.message.impl;

import com.alibaba.fastjson.JSONObject;
import com.travel.api.beans.request.message.EmailRequest;
import com.travel.api.beans.request.message.SMSRequest;
import com.travel.api.service.BaseService;
import com.travel.api.utils.ResultConstant;
import com.travel.api.service.message.MessageService;
import com.travel.api.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MessageServiceImpl
 * @Author liguangyao
 * @Date 23/8/18 下午2:49
 * @Version 1.0
 **/
@Service
@Slf4j
public class MessageServiceImpl extends BaseService implements MessageService {

    @Value("${JUHE_APPKEY}")
    private String JUHE_APPKEY;

    @Value("${JUHE_SMS_TEMPLATE_ID}")
    private String JUHE_SMS_TEMPLATE_ID;

    @Value("${spring.mail.username}")
    private String SENDER;

    @Value("${SMS_URL}")
    private String SMS_URL;

    @Value("${SMS_VALIDATION_PREFIX}")
    private String SMS_VALIDATION_PREFIX;

    @Value("${EMAIL_NUMBER_PREFIX}")
    private String EMAIL_NUMBER_PREFIX;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    @Async
    public String sendSMS(String mobile, String code) {
        String result =null;
        Map<String ,String> params = new HashMap<String ,String>(); //请求参数
        params.put("mobile",mobile); //接收短信的手机号码
        params.put("tpl_id",JUHE_SMS_TEMPLATE_ID); //短信模板ID，请参考个人中心短信模板设置
        params.put("tpl_value","#code#=" + code); //变量名和变量值对
        params.put("key",JUHE_APPKEY); //应用APPKEY(应用详细页查询)
        params.put("dtype",""); //返回数据的格式,xml或json，默认json
        try {
            result = com.travel.api.util.SendRequestUtils.net(SMS_URL, params, "GET");
            JSONObject object = JSONObject.parseObject(result);
            if(object.getInteger("error_code")==0){
                log.info("[短信发送] 信息:{}", object.get("result"));
            }else{
                log.info("[短信发送] 信息:{}:{}",object.get("error_code"), object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Map<String, Object> validationSMS(SMSRequest request) {
        String validation = RedisUtil.get(SMS_VALIDATION_PREFIX + request.getMobile()); // REDIS存储的验证码
        if(StringUtils.isEmpty(validation)) {
            return fail(ResultConstant.SMS_TIMEOUT, "验证码已失效,请重新发送");
        }
        if(validation.equals(request.getCode())) {
            return success("短信验证码正确",null);
        }
        return fail(ResultConstant.SMS_VALIDATION_NO,"短信验证码不正确");
    }

    @Override
    @Async
    public void sendEmail(String email, String code) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SENDER); //寄件人
        message.setTo(email); //收件人
        message.setSubject("Travel"); //主题
        message.setText("您的验证码是: " + code); //内容
        try {
            mailSender.send(message);
        } catch (MailException e) {
            log.error(e.getMessage());
        }
        log.info("[邮箱发送] 收件人:{}, 验证码:{}", email, code);
    }

    @Override
    public Map<String, Object> validationEmail(EmailRequest request) {
        String code = RedisUtil.get(EMAIL_NUMBER_PREFIX + request.getEmail());
        if(StringUtils.isEmpty(code)) {
            return fail(ResultConstant.EMAIL_TIMEOUT, "验证码已失效,请重新发送");
        }
        if(code.equals(request.getCode())) {
            return success();
        }
        return fail(ResultConstant.EMAIL_VALIDATION_NO, "邮箱验证码不正确");
    }
}
